<template>
  <div class="app-container">
    <el-card class="box-card search-div">
      <el-form :inline="true" :model="listQuery" ref="queryForm" v-show="showSearch">
       <el-form-item label="数据源" prop="datasourceId">
         <el-select v-model="listQuery.datasourceId" filterable placeholder="请选择数据源">
          <el-option v-for="item in datasourceOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
       </el-form-item>
       <el-form-item label="表名称" prop="tableName">
         <el-input v-model="listQuery.tableName" placeholder="请输入表名称" clearable @keyup.enter.native="handleSearch" />
       </el-form-item>
       <el-form-item label="表描述" prop="tableComment">
         <el-input v-model="listQuery.tableComment" placeholder="请输入表描述" clearable @keyup.enter.native="handleSearch" />
       </el-form-item>
        <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
        <el-button @click="handleResetQuery" icon="el-icon-refresh">重置</el-button>
      </el-form>
    </el-card>
    <el-card class="box-card">
      <el-table :data="tableList" v-loading.body="loading" border fit highlight-current-row class="table-list">
        <el-table-column label="序号" type="index" min-width="5%"/>
        <el-table-column label="表名称" align="center" prop="tableName" width="200"/>
        <el-table-column label="表描述" align="center" prop="tableComment" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="160" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  width="250">
          <template slot-scope="scope">
            <el-button plain type="violet" @click="handleEditTable(scope.row)" v-hasPermi="['tool_gen_edit']">编辑</el-button>
            <el-button plain @click="handlePreview(scope.row)" v-hasPermi="['tool_gen_preview']">预览</el-button>
            <el-button plain type="success"  @click="handleGenTable(scope.row)" v-hasPermi="['tool_gen_code']">生成代码</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </el-card>

    <!--编辑-->
    <el-dialog title="代码配置" :visible.sync="showDialog" center fullscreen :close-on-click-modal="false">
      <el-steps :active="steps_active" finish-status="success">
        <el-step title="字段信息"></el-step>
        <el-step title="配置信息"></el-step>
      </el-steps>

      <!--table列信息-->
      <el-table :data="columns" row-key="columnName" border fit highlight-current-row v-if="this.steps_active==0" :max-height="tableHeight">
        <el-table-column label="序号" type="index" min-width="5%"/>
        <el-table-column label="字段列名" prop="columnName" min-width="10%" :show-overflow-tooltip="true"/>
        <el-table-column label="字段描述" min-width="10%">
          <template slot-scope="scope">
            <el-input v-model="scope.row.columnComment"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="物理类型" prop="columnType" min-width="10%"/>
        <el-table-column label="Java类型" min-width="11%">
          <template slot-scope="scope">
            <el-select v-model="scope.row.javaType">
              <el-option label="Long" value="Long" />
              <el-option label="String" value="String" />
              <el-option label="Integer" value="Integer" />
              <el-option label="Double" value="Double" />
              <el-option label="BigDecimal" value="BigDecimal" />
              <el-option label="Date" value="Date" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="java属性" min-width="10%">
          <template slot-scope="scope">
            <el-input v-model="scope.row.javaField"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="编辑" min-width="5%">
          <template slot-scope="scope">
            <el-checkbox true-label="1" v-model="scope.row.isEdit"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="列表" min-width="5%">
          <template slot-scope="scope">
            <el-checkbox true-label="1" v-model="scope.row.isList"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="查询" min-width="5%">
          <template slot-scope="scope">
            <el-checkbox true-label="1" v-model="scope.row.isQuery"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="必填" min-width="5%">
          <template slot-scope="scope">
            <el-checkbox true-label="1" v-model="scope.row.isRequired"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="显示类型" min-width="12%">
          <template slot-scope="scope">
            <el-select v-model="scope.row.htmlType">
              <el-option label="文本框" value="input" />
              <el-option label="文本域" value="textarea" />
              <el-option label="数字框" value="number" />
              <el-option label="下拉框单选" value="selectSingle" />
              <el-option label="下拉框多选" value="selectMultiple" />
              <el-option label="日期控件" value="datetime" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="字典类型" min-width="12%">
          <template slot-scope="scope">
            <el-select v-model="scope.row.dictType" clearable filterable placeholder="请选择">
              <el-option
                v-for="dict in dictOptions"
                :key="dict.code"
                :label="dict.dictValue"
                :value="dict.code">
            </el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>

     <!--配置信息-->
      <el-form ref='genInfoForm' :model="tableInfoForm" :rules="genRules" label-width="150px" v-if="this.steps_active==1">
        <el-row>
          <el-col :span="12">
            <el-form-item label="表名称" prop="tableName">
              <el-input :disabled="true" v-model="tableInfoForm.tableName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="tplCategory">
              <span slot="label">生成模板</span>
              <el-select v-model="tableInfoForm.tplCategory" style="width: 100%;">
                <el-option label="单表（增删改查）" value="crud" />
                <el-option label="树表（增删改查）" value="tree" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="作者" prop="functionAuthor">
              <el-input placeholder="请输入" v-model="tableInfoForm.functionAuthor" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="moduleName">
              <span slot="label">
                生成模块名
                <el-tooltip content="可理解为子系统名，例如 system" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
              <el-input v-model="tableInfoForm.moduleName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="实体类名称" prop="className">
              <el-input placeholder="请输入" v-model="tableInfoForm.className" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="tableComment">
              <span slot="label">
                生成功能名
                <el-tooltip content="用作类描述，例如 用户" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
              <el-input v-model="tableInfoForm.tableComment" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item>
              <span slot="label">上级菜单<el-tooltip content="分配到指定菜单下，例如 系统管理" placement="top"><i class="el-icon-question"></i></el-tooltip></span>
              <treeselect :multiple="false" v-model="tableInfoForm.parentMenuId" :options="menus" :load-options="loadOptions" :show-count="true" placeholder="请选择系统菜单" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-show="tableInfoForm.tplCategory == 'tree'">
          <h4 class="form-header">其他信息</h4>
          <el-col :span="8">
            <el-form-item>
              <span slot="label">
                树编码字段
                <el-tooltip content="树显示的编码字段名， 如：dept_id" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
              <el-select v-model="tableInfoForm.treeCode" placeholder="请选择">
                <el-option
                  v-for="column in columns"
                  :key="column.columnName"
                  :label="column.columnName + '：' + column.columnComment"
                  :value="column.columnName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <span slot="label">
                树父编码字段
                <el-tooltip content="树显示的父编码字段名， 如：parent_Id" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
              <el-select v-model="tableInfoForm.treeParentCode" placeholder="请选择">
                <el-option
                  v-for="column in columns"
                  :key="column.columnName"
                  :label="column.columnName + '：' + column.columnComment"
                  :value="column.columnName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <span slot="label">
                树名称字段
                <el-tooltip content="树节点的显示名称字段名， 如：dept_name" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
              <el-select v-model="tableInfoForm.treeName" placeholder="请选择">
                <el-option
                  v-for="column in columns"
                  :key="column.columnName"
                  :label="column.columnName + '：' + column.columnComment"
                  :value="column.columnName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="showDialog = false">取 消</el-button>
        <el-button size="medium" type="primary" @click="steps_active=0" v-if="this.steps_active!=0">上一步</el-button>
        <el-button size="medium" type="primary" @click="steps_active=1"  v-if="this.steps_active!=1">下一步</el-button>
        <el-button size="medium" type="primary" @click="onSave()"  v-if="this.steps_active==1">保存</el-button>
      </div>
    </el-dialog>

    <!-- 预览界面 -->
    <el-dialog :title="preview.title" :visible.sync="preview.open" center fullscreen :close-on-click-modal="false">
      <el-tabs v-model="preview.activeName">
        <el-tab-pane
          v-for="(value, key) in preview.data"
          :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
          :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
          :key="key"

        >
          <pre>{{ value }}</pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import * as gen from "./js/gen";
import * as menu from '../system/menu/js/menu'
import {getTopDictList} from '../system/dict/js/dict'
import {select} from './js/datasource'
import { download } from '@/utils/ruoyi'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Gen",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 表数据
      tableList: [],
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      listQuery: {
        page: 1, limit: 10, datasourceId:'',tableName: '', tableComment: ''
      },
      columns:[],
      showDialog: false,
      steps_active: 0,
      // 表格的高度
      tableHeight: document.documentElement.scrollHeight - 245 + "px",
      tableInfoForm:{'id':'','columns':[],'dataSourceId':'','tableName':'','tableComment':'','className':'','remark':'','functionAuthor':'','tplCategory':'crud','moduleName':''},
      genRules: {
        tableName: [{ required: true, message: "请输入表名称", trigger: "blur" }],
        tableComment: [{ required: true, message: "请输入表描述", trigger: "blur" }],
        className: [{ required: true, message: "请输入实体类名称", trigger: "blur" }],
        functionAuthor: [{ required: true, message: "请输入作者", trigger: "blur" }],
        tplCategory: [{ required: true, message: "请选择生成模板", trigger: "blur" }],
        moduleName: [{ required: true, message: "请输入生成模块名", trigger: "blur" }],
      },
      dictOptions:[],
      // 菜单
      menus:[],
      // 预览参数
      preview: {
        open: false,
        title: "代码预览",
        data: {},
        activeName: "domain.java"
      }
      ,datasourceOptions:[]
    }
  },
 computed: {
   ...mapGetters(['permissions'])
  },
  created() {
    this.init()
    this.initDatasourceSelect()
  },
  methods: {
    init(){
      getTopDictList("region").then(response => {
        this.dictOptions = response.data;
      })
    },
    loadOptions(){},
    initDatasourceSelect(){
      let that = this
      select().then(response => {
          that.datasourceOptions = response.data
          that.listQuery.datasourceId=that.datasourceOptions[0].value
          this.getList()
        }
      )
    },
    getList() {
      this.loading = true;
      gen.listTable(this.listQuery).then(response => {
          this.tableList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        }
      )
    },
    handleSearch() {
      this.listQuery.page = 1
      this.getList()
    },
    handleResetQuery(){
      this.resetForm("queryForm")
      this.listQuery.datasourceId=this.datasourceOptions[0].value
      this.handleSearch()
    },
    /** 生成代码操作 */
    handleGenTable(row) {
      download('/tools/gen/download',{"dataSourceId":this.listQuery.datasourceId,"tableName":row.tableName})
    },
    /** 预览按钮 */
    handlePreview(row) {
      gen.previewTable(this.listQuery.datasourceId,row.tableName).then(response => {
        this.preview.data = response.data;
        this.preview.open = true;
      });
    },
    /** 修改按钮操作 */
    handleEditTable(row) {
      this.showDialog = true
      this.steps_active = 0
      let that = this
      this.$nextTick(() => {
        //初始化列
        gen.getGenTable(this.listQuery.datasourceId,row.tableName).then(response => {
            let info = response.data.info;
            that.columns = response.data.columns;
            that.tableInfoForm.tableName = row.tableName
            that.tableInfoForm = info
            that.tableInfoForm.tableComment = info.tableComment?info.tableComment:row.tableComment
            that.tableInfoForm.functionAuthor = info.functionAuthor?info.functionAuthor:'moon'
          })
       })
       //查询所有菜单
       menu.getAllMenuNotButton().then(response => {
         this.menus = response.data
       })
    },
    back(){
      this.steps_active--
    },
    next(){
      this.steps_active=1
    },
    //保存
    onSave(){
      this.$refs['genInfoForm'].validate((valid) => {
        if (valid) {
            this.tableInfoForm.columns = this.columns
            this.tableInfoForm.dataSourceId = this.listQuery.datasourceId
            gen.updateGenTable(this.tableInfoForm).then(response => {
               this.menus = response.data
               this.steps_active=1
               this.showDialog = false
               this.$message({ type: 'success', message: '操作成功!' })
           })
          }
       })
    }
  }
};
</script>
